package com.example.a2032.activity

import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.a2032.MainActivity
import com.example.a2032.R
import com.example.a2032.Utils.SharedPreferenceUtils
import com.example.a2032.Utils.Utils
import com.example.a2032.adapter.LanguageAdapter
import kotlinx.android.synthetic.main.activity_language.*
import kotlinx.android.synthetic.main.layout_setting_title.*
import java.util.*

class LanguageActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_language)
        init();
    }

    fun init() {
        val title = intent.getStringExtra(SettingActivity.KEY_SettingTitle)
        tv_title.text = title
        iv_title.setOnClickListener {
            finish()
        }
        val arrayLanguage= arrayOf(Locale.ENGLISH.language,Locale.SIMPLIFIED_CHINESE.language)
        val position=Utils.getSetLanguagePosition(arrayLanguage)
        val languageAdapter = LanguageAdapter(resources.getStringArray(R.array.language_array))
        languageAdapter.selectedPosition=position
        languageAdapter.setItemClickListener(object : LanguageAdapter.OnItemClickListener {
            override fun onItemClick(position: Int) {
                super.onItemClick(position)
                changeLanguage(position)
            }
        })
        val manager = LinearLayoutManager(this).apply {
            orientation = LinearLayoutManager.VERTICAL
        }
        recyclerViewLanguage.apply {
            layoutManager = manager
            adapter = languageAdapter
        }

    }

    private fun changeLanguage(position: Int) {
        var locale = when (position) {
            0 -> Locale.ENGLISH
            else -> Locale.SIMPLIFIED_CHINESE
        };
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_Language, locale.language);
        Utils.changeLanguage(application, locale)
        val intent = Intent(this, MainActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        startActivity(intent)
        finish()
    }
}